"""Header_Information
------------------------------------
    File_Name: database
    Author: RR9
    Date: 2024/10/12
    Description: 数据库相关工具
------------------------------------
"""


# 防止传入None,'',0等情况
# _no_value = object()


def branch_execute(cursor, sql, args):
    """是否有绑定变量"""
    if args is None:
        cursor.execute(sql)
    else:
        cursor.execute(sql, args)


def fetch_column_dict(cursor, sql, args=None) -> list:
    """
    获取查询sql的所有字段
    """
    branch_execute(cursor, sql, args)
    column_names = [d[0] for d in cursor.description]
    return column_names


def fetch_all_dict(cursor, sql, args=None) -> list[dict]:
    """
    description: 获取全部结果(多个元组组成的列表)
    """
    branch_execute(cursor, sql, args)
    # 所有表字段
    column_names = [d[0] for d in cursor.description]
    # list of data items
    all_rows = list(cursor.fetchall())
    # 将None 转换为''
    rows = []
    for mx in range(len(all_rows)):
        rows.append(tuple(['' if m is None else m for m in all_rows[mx]]))
    result = [dict(zip(column_names, row)) for row in rows]
    return result
